/**
 * Created by foxit on 15-10-20.
 */
define(function (require, exports, module) {
    var CMISService = require("./CMISService");      
    var FolderTree = require("./component/FolderTree");
    var FolderList  = require("./component/FolderList");  
    $(function() {
        var error = UCX_Utils.getUrlParam('error');
        if (error){
            UCX_Utils.alert("Error", error);
        }      
        var curFolderId = null;
        CMISService.getFolderTree().done(function(data) {      
            var folder_action = null;
            if (isAdmin) {
                folder_action = React.createElement("li", {className: "fa fa-trash-o", name: "delete"}, "");              
            }
            ReactDOM.render(React.createElement(FolderTree, {
                    data: data,
                    option: {
                        id: 'folderNav',
                        style: 'tree-solid-line'
                    }
            }, folder_action), $("#document-navigation .tree-box")[0]);

            $('#folderNav').on('clickNode', function(e, node) {
                $('#folder_selected').html(node.path);
                updateFolderList(node.id);
            });      

            $('#folderNav').on('action.delete', function(e, node) {     
                UCX_Utils.confirm('Comfirm delete this folder?', function() {
                    CMISService.removeFolder(node).fail(function(response) {
                        UCX_Utils.alert('Error', response.message);
                    });
                });
            });

        });

        var fileSelected;

        //change_icon

        $(".change_icon").click(function() {
            if ($('.list_nav').is(":visible") === true) {
                $(this).find('.up-down').attr("class", "fa fa-chevron-down up-down");
            } else {
                $(this).find('.up-down').attr("class", "fa fa-chevron-up up-down");
            }
        });            

        //nature_box open and hide

        $('.nature').click(function() {
            $(this).parent().parent().find('.article_box').css('bottom', '200px');
        });
        $('.icon_hide_nature').click(function() {
            $(this).parent().parent().find('.article_box').css('bottom', '45px');
        });        

        //nature_box open and hide
        $('.btn_hide_split_view_master_wrap').click(function() {
            if ($('.split_view_master_wrap').is(":visible") === true) {
                $('.split_view_master_wrap').css({
                    'display': 'none'
                });
                $('.split_view_slave_wrap').css({
                    'left': '0px'
                });
            } else {
                $('.split_view_master_wrap').css({
                    'display': 'block'
                });
                $('.split_view_slave_wrap').css({
                    'left': '330px'
                });
            }
        });    

        $(".maillist_content_wrap_absolute_full").on("clickItem", ".maillist_content_wrap", function(event, node) {
            if (node.type === "cmis:folder"){
                updateFolderList(node.id);
            }       
            else{
                previewByDocumentId(node.id);
            } 
        });
        function updateFolderList(id) {
            curFolderId = id;
            $(".maillist_content_wrap_absolute_full").loading();
            CMISService.getFolderChildren(id)
                .done(function(response) {
                    if (response.parentId != 'root') {
                        $("#parentFolder").attr('onclick', 'updateFolderList(\'' + response.parentId + '\')');
                    } else {
                        $("#parentFolder").attr('onclick', 'javascript:;');
                    }

                    var headerNum = (response.folderNum ? response.folderNum : 0) + '个目录,' + (response.docNum ? response.docNum : 0) + '个文档';
                    $(".maillist_header_wrap").find('h5').html(headerNum);
                    React.render(React.createElement(FolderList, {
                        data: response,
                        option: {
                            style: 'tree-plus-minus',
                            id: 'create-folder-tree',
                            enableSelect: true
                        }
                    }), $(".maillist_content_wrap_absolute_full")[0]);
                    $(".maillist_content_wrap").attr("objid", id);
                })
                .always(function() {
                    $(".maillist_content_wrap_absolute_full").endLoad();
                });           
        }

        function previewByDocumentId(documentID) {      
            $('#preview-area').css("display", "block");
            $('#docViewer').empty();       
            fileSelected = documentID;			
            window.continuous = true;
            window.defaultZoom = 'FitWidth';
            webreader.initViewerForPreView("https://" + window.document.domain + "/archive/preview-pdf?objectId=" + documentID);
	        $(window).resize();
        }

        $("#view-histroy-version").click(function() {
            if (fileSelected) {
                var obj_id = fileSelected;
                $.ajax({
                    type: "GET",
                    url: "/archive/get-all-versions?objectId=" + obj_id,
                    dataType: "json",
                    success: function(data) {
                        var tempHtml = '';
                        for (var i = 0; i < data.length; i++) {
                            var updateBy = data[i].LastModifiedBy;
                            var updateDate = data[i].LastModificationDate;
                            var label = data[i].Label;
                            tempHtml += '<div class="row panel-body">' +
                                '<div class="col-lg-10">' + new Date(updateDate).toLocaleString() + ' 被' + updateBy + '更新</div>' +
                                '<div class="col-lg-2">版本' + label + '</div>' +
                                '</div>';
                        }
                        $("#getAllVersionList").html(tempHtml);
                        $("#viewHistoryVersionModal").modal("show");
                        $("#versionCount").html(data.length);
                    },
                    error: function(e) {
                        alert(e);
                    }
                });
            } else {
                UCX_Utils.alert("Alert", "Please select a document first!");
            }
        });

        $("#open-upload-new-version").click(function() {
            if (fileSelected) {
                $("#upload-new-version").find("[name='object_id']").val(fileSelected);
                $("#upload-new-version").modal("show");
            } else {
	            UCX_Utils.alert("Alert", "please select a document first!");
	            return;
            }
        });

        $("#download-file").click(function() {
            if (fileSelected) {
                window.open('/archive/download-file?objectId=' + fileSelected, '_self');
            } else {
	            UCX_Utils.alert("Alert", "please select a document first!");
	            return;
            }
        });

        $("#backRoot").on("click", function() {
            updateFolderList(window.myFolderId);
        });   

        $('#removeDocument').on('click', function() {
            var doc= getSelectedDocument();
            if (!doc) {
                UCX_Utils.alert("Alert", "please select a document first!");
                return;
            }
            var folderId = getFolderId();

            UCX_Utils.confirm('Comfirm delete this document?', function() {
                CMISService.removeDocument(doc, folderId).done(function(response) {
                    if (response.errorCode === 0) {
                         updateFolderList(curFolderId);
                    } else {
                        UCX_Utils.alert('Error', response.message);
                    }
                });
            });
        });

        $('#setAcl').on("click", function() {
            var folderId = getFolderId();
            if(folderId !==null && folderId !== undefined){
                $('#folder_obj_id').val(folderId);
                CMISService.getAcl(folderId).done(function(data){
                    $('#folder-permissions-select').html('');
                    //var html = '<div class="col-lg-6">用户</div><div class="col-lg-6">权限</div>';
                    //$.each(data,function(i, value){
                    //    $.each(value.permissions,function(j,permissions){
                    //        html += '<div class="col-lg-6">'+value.principalId+'</div>';
                    //        html += '<div class="col-lg-6">'+permissions+'</div>';
                    //    });
                    //
                    //});
                    var html = '';
                    var list = '';

                    $.each(data,function(i, value){
                        $.each(value.permissions,function(j,permissions){
                            html += '<option value="'+value.principalId+'|'+permissions+'">'+value.principalId+'|'+permissions+'</option>';
                            list += '<div class="hide-permission hide" permission="'+ value.principalId+'|'+permissions +'"><input class="acl-send-user-list" name="Acl[user][]" value="'+ value.principalId +'"></input><input class="acl-send-permission-list" name="Acl[permission][]" value="'+ permissions +'"></input></div>';
                        });

                    });
                    $('#set-acl-form').append(list);
                    $('#folder-permissions-select').append(html);
                });
                adjustSizeForMultipleSelect();
                $('#directory-permissions').modal("show");
            }else{
                UCX_Utils.alert("Tips", "please select a folder first!");
            }

        });

        $('#add-permissions').on("click",function(){
            var dom = $(this).parent().parent(),
                inputs = dom.find('input'),
                user = inputs[0].value,
                selects = dom.find('select'),
                permission  = selects[0].value;

            if(user == ''){
                dom.addClass("has-error");
                dom.find('.help-block').html('请输入用户');
                return;
            }

            $('#folder-permissions-select').append('<option value="' + user + '|' + permission +'">' + user + '|' + permission + '</option>');

            dom.after('<div class="hide-permission hide" permission="'+ user+'|'+permission +'"><input class="acl-send-user-list" name="Acl[user][]" value="'+ user +'"></input><input class="acl-send-permission-list" name="Acl[permission][]" value="'+ permission +'"></input></div>');

            dom.removeClass("has-error").find('.help-block').html('');
            dom.find('input').val('');
            adjustSizeForMultipleSelect();
        });

        $('#remove-permissions').on("click",function(){
            var selected = $('#folder-permissions-select option:selected');
            for(var i = 0, l=selected.length; i< l; i++){
                var selectedValue = selected[i].value;
                $input = $("div[permission='"+selectedValue+"']");
                $input.remove();
            }
            $('#folder-permissions-select option:selected').remove();
            adjustSizeForMultipleSelect();
        });

        function adjustSizeForMultipleSelect() {
            var size = $("#folder-permissions-select option").length;
            if (size < 3) {
                size = 3;
            }
            $("#folder-permissions-select").prop("size", size);
        }

        $('#copyTo').on("click", function() {
            var doc = getSelectedDocument();
            if (!doc) {
                UCX_Utils.alert("Alert", "please select a document first!");
                return;
            }
            $('#copy-to').modal("show");
        });
        $('#moveTo').on("click", function() {
            var doc= getSelectedDocument();
            if (!doc) {
                UCX_Utils.alert("Alert", "please select a document first!");
                return;
            }
             $('#move-to').modal("show");
        });

        $('#copy-to').on('show.bs.modal', function() {
            CMISService.getFolderTree().done(function(data) {
                React.render(React.createElement(FolderTree, {
                    data: data,
                    option: {
                        style: 'tree-plus-minus',
                        id : 'copy-to-tree',
                        enableSelect: true
                    }
                }), $("#copy-to .model-nav-list-box")[0]);
            });
        }).on("click", ".btn-warning", function(event, data) {
            var doc = getSelectedDocument();
            var selectedNode = $("#copy-to-tree").data("getSelectedNode")()[0];
            if (selectedNode) {
                CMISService.copyTo(doc, selectedNode.id)
                    .fail(function(response) {
                        UCX_Utils.alert('Error', response.message);
                    });
                $('#copy-to').modal('hide');
            }
        });

        $('#move-to').on('show.bs.modal', function() {
            CMISService.getFolderTree().done(function(data) {
                React.render(React.createElement(FolderTree, {
                    data: data,
                    option: {
                        style: 'tree-plus-minus',
                        enableSelect: true,
                        id : 'move-to-tree'
                    }
                }), $("#move-to .model-nav-list-box")[0]);
            });
        }).on('click', '.btn-warning', function(event, data) {
            var doc = getSelectedDocument();
            var sourceFolderId = getFolderId();    
            var selectedNode = $("#move-to-tree").data("getSelectedNode")()[0];
            if (selectedNode) {         
                CMISService.moveTo(doc, sourceFolderId, selectedNode.id)
                    .done(function() {
                        updateFolderList(curFolderId);
                    })
                    .fail(function(response) {
                        UCX_Utils.alert('Error', response.message);
                    });
                $('#move-to').modal('hide');
            }
        });

        $('#create-folder').on('show.bs.modal', function() {
            CMISService.getFolderTree().done(function(data) {
                React.render(React.createElement(FolderTree, {
                    data: data,
                    option: {
                        style: 'tree-plus-minus',
                        id: 'create-folder-tree',
                        enableSelect: true
                    }
                }), $("#tree_select .panel-body")[0]);

                $('#create-folder-tree').on('clickNode', function(e, node) {
                    $("#createfolder-repofolder").val(node.path);
                });
            });
        });

        $('#upload-document').on('show.bs.modal', function() {         
            if ($("#upload_file_tree .panel-body").length === 0) return;

            CMISService.getFolderTree().done(function(data){
                React.render(React.createElement(FolderTree, {
                    data: data,
                    option: {
                        style: 'tree-plus-minus',
                        id: 'upload-document-tree'
                    }
                }), $("#upload_file_tree .panel-body")[0]);               
            });

            $('#upload-document-tree').on('clickNode', function(e, node) {
                $("#uploadfile-folderpath").val(node.path);
            });
        });

       

        function getSelectedDocument() {               
            return  $(".maillist_content_wrap").data("getSelectedItem")();
        }

        function getFolderId() {
            return $(".maillist_content_wrap").attr("objid");
        }
    });
});
